#!/usr/bin/python
#
# Generic daemonizer for python programs.
#
#  Based on Jurgen Hermanns Python recipe:
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66012
#
LOGFILE = '/var/log/monitord.log'
PIDFILE = '/var/run/monitord.pid'

from monitor import monitor
ENTRYPOINT = monitor.main

import sys, os

class Log:
    'Always-flushing log.'
    # Probably overkill unless interfacing with unsafe C code...
    # Python doesn't crash much.
    #
    # Not like it's going to hurt performance, though, so okay.
    # Could insert timestamps here too :)
    def __init__(self, f):
        self.f = f
    def write(self, s):
        self.f.write(s)
        self.f.flush()

def main():
    'Program entry point once fork magic is done.'
    #change to data directory if needed
    os.chdir("/root") # this used to be /root/data, but that's not guaranteed...
    #redirect outputs to a logfile
    sys.stdout = sys.stderr = Log(open(LOGFILE, 'a+'))
    #ensure the that the daemon runs a normal user
    os.setegid(2) # this used to set both gid/uid to 103   
    os.seteuid(2) # but why not use 'daemon' instead?
    #start the actual user program here:
    ENTRYPOINT()

if __name__=="__main__":
    # do the UNIX double-fork magic, see Stevens' "Advanced
    # Programming in the UNIX Environment" for details (ISBN 0201563177)
    try:
        pid = os.fork()
        if pid > 0:
            # exit first parent
            sys.exit(0)
    except OSError, e:
        print >>sys.stderr, "fork #1 failed: %d (%s)" % (e.errno, e.strerror)
        sys.exit(1)

    # decouple from parent environment
    os.chdir("/")   #don't prevent unmounting....
    os.setsid()
    os.umask(0)

    # do second fork
    try:
        pid = os.fork()
        if pid > 0:
            # exit from second parent, print eventual PID before
            #print "Daemon PID %d" % pid
            open(PIDFILE,'w').write("%d"%pid)
            sys.exit(0)
    except OSError, e:
        print >>sys.stderr, "fork #2 failed: %d (%s)" % (e.errno, e.strerror)
        sys.exit(1)

    # start the daemon main loop
    main()


